
package com.suarte.core.hibernate;
import com.suarte.core.Product;
import com.suarte.core.Resolution;
import com.suarte.core.WorkType;
import com.suarte.core.dao.ProductDao;
import java.util.ArrayList;
import java.util.List;

import org.appfuse.dao.hibernate.GenericDaoHibernate;

import org.springframework.stereotype.Repository;

/**
 * @date   Dec 20, 2010
 * @author Ggutierrez
 */
@Repository("productDao")
public class ProductDaoHibernate extends GenericDaoHibernate<Product, Long> implements ProductDao {
    
    public ProductDaoHibernate() {
        super(Product.class);
    }

    public List<Product> findByDescription(String description) {
        return getHibernateTemplate().find("from Product where upper(description) like ?", "%".concat(description.toUpperCase()).concat("%"));
    }

    public List<Product> findByCode(String code) {
        return getHibernateTemplate().find("from Product where code like ?", "%".concat(code.toUpperCase()).concat("%"));
    }

    public List<Product> findProducts(String code, String description, Resolution resolution, WorkType workType) {
        String hql = "from Product this join fetch this.resolution resolution join fetch this.workType workType " +
                     " where 1 = 1";
        List args = new ArrayList();

        if (!isBlank(code)){
            args.add(code);
            hql += " and this.code like ?";
        }
        if (!isBlank(description)) {
            args.add(description.toUpperCase().concat("%"));
            hql += " and upper(ltrim(rtrim(this.description))) like upper(ltrim(rtrim(?)))";
        }
        if (resolution != null) {
            args.add(resolution);
            hql += " and resolution = ?";
        }
        if (workType != null) {
            args.add(workType);
            hql += " and workType = ?";
        }

        List results = getHibernateTemplate().find(hql, args.toArray());
        return results;
    }

    private boolean isBlank(String value) {
        return value == null || value.trim().length() == 0;
    }
}
